package com.shiroha.common.event;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.shiroha.common.utils.JsonUtils;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;

public class ServiceEvent extends ApplicationEvent {
    @Getter
    private final ServiceEventType eventType;
    private final String data;

    private ServiceEvent(Object source, ServiceEventType eventType, String data) {
        super(source);
        this.eventType = eventType;
        this.data = data;
    }

    public static ServiceEvent create(Object source, ServiceEventType eventType, Object data) throws JsonProcessingException {
        String dataString = JsonUtils.serialize(data);
        return new ServiceEvent(source, eventType, dataString);
    }

    public <T> T getDataAsType(Class<T> clazz) throws JsonProcessingException {
        return JsonUtils.deserialize(data, clazz);
    }

    public <T> T getDataAsType(TypeReference<T> typeReference) throws JsonProcessingException {
        return JsonUtils.deserialize(data, typeReference);
    }
}
